# coding=utf-8
import sys
import os
from os import path, access, W_OK
from urlparse import urlparse
from BeautifulSoup import BeautifulSoup
import cookielib
import urllib2
import urllib
import re
from crunchy_video import CrunchyPlayback
#import pdb

#pdb.set_trace()
xmlSource = sys.argv[1]
#xml decoding, useful for region blocked videos. just download the xml using a proxy or the like.
if xmlSource.lower().endswith(".xml"):
	xmlSource = open(sys.argv[1])
	xml = xmlSource
	player_revision = '20130614072121.a6d69c63cc5ec3d72835f991b7d014be' #this would need updating every so often

#url decoding
else:
	page_url = sys.argv[1]
	vid_id = page_url[-6:]
	xml = "http://www.crunchyroll.com/xml/?req=RpcApiVideoPlayer_GetStandardConfig&media_id="+vid_id+"&video_format=106&video_quality=60&auto_play=1&show_pop_out_controls=1"
	url_parse = urlparse(xml)
	cookie_jar = cookielib.LWPCookieJar()
	cookie = urllib2.HTTPCookieProcessor(cookie_jar)
	opener = urllib2.build_opener(cookie)
	html = urlparse(page_url)
	CP = CrunchyPlayback()
	html = CP.downloadHTML(page_url)
	htmlsoup = BeautifulSoup(html)
	player_revision = re.findall(r"flash\\/.+\\/StandardVideoPlayer.swf", str(htmlsoup))
	player_revision = player_revision.pop()
	player_revision = re.findall(r"[0-9a-z.]{47}", str(player_revision))
	player_revision = player_revision.pop()
	opener.addheaders =[('Referer', 'http://static.ak.crunchyroll.com/flash/'+player_revision+'/StandardVideoPlayer.swf'),('Host','www.crunchyroll.com'),('Content-type','application/x-www-form-urlencoded')]
	opener.params = {'current_page' : 'http://www.crunchyroll.com/'}
	req = urllib2.Request(xml, urllib.urlencode(opener.params))
	res = opener.open(req)
	xml = res.read()

soup = BeautifulSoup(xml)
host = soup.find('host').string
url1 = re.findall(".+/ondemand/", host)
url1 = url1.pop()
url2 = re.findall("ondemand/.+", host)
url2 = url2.pop()
file = soup.find('file').string
CP = CrunchyPlayback()

command = open('Command.bat', 'w')
try:
	command.write('..\\rtmpexplorer\\rtmpdump -r "'+url1+'" -a "'+url2+'" -f "WIN 11,8,800,50" -W "http://static.lln.crunchyroll.com/flash/'+player_revision+'/ChromelessPlayerApp.swf" -p "'+page_url+'" -y "'+file+'" -o "video.flv"')
except NameError:
	command.write('..\\rtmpexplorer\\rtmpdump -r "'+url1+'" -a "'+url2+'" -f "WIN 11,8,800,50" -W "http://static.lln.crunchyroll.com/flash/'+player_revision+'/ChromelessPlayerApp.swf" -p "www.crunchyroll.com" -y "'+file+'" -o "video.flv"')
command.close()